<div class="main">
	<form class="form-inline" role="form">
		<div class="form-group">
			<label> 机器列表: </label>
			<button type="button" class="btn btn-success" data-target="#addServerModal" data-toggle="modal"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp;机器</button>
			<button type="button" data-toggle="tooltip" title="批量修改预警阈值" class="btn btn-success" onclick="batchUpdateServerAlarmConfig()"><span class="glyphicon glyphicon-cog" aria-hidden="true"></span>&nbsp;预警阈值</button>
		</div>
	</form>
	<hr/>
	<table class="table table-striped table-hover" id="serverTable" style="margin-top: 0px;word-break:break-all; word-wrap:break-all;">
		<thead>
			<colgroup>
			  <col width='20px'>
			  <col>
			  <col width='120px'>
			  <col>
			  <col>
			  <col width='120px'>
			  <col>
			  <col>
			  <col>
			  <col>
			  <col>
			  <col>
			  <col>
			  <col>
			  <col>
			  <col>
			  <col width='140px'>
			  <col>
			</colgroup>
			<tr>
				<td><input class="pointer" type="checkbox" name="monitor" id="checkAll" onclick="checkAll(this)" data-toggle="tooltip" title="单击全选或反选"/></td>
				<td>序号</td>
				<td>ip</td>
				<td>host</td>
				<td data-toggle="tooltip" title="cpu核数">cpu</td>
				<td data-toggle="tooltip" title="使用/总内存">内存</td>
				<td data-toggle="tooltip" title="一分钟load">load1</td>
				<td data-toggle="tooltip" title="磁盘读速率 单位K/s">ior</td>
				<td data-toggle="tooltip" title="磁盘写速率 单位K/s">iow</td>
				<td data-toggle="tooltip" title="磁盘io速率 交互次数/s">iops</td>
				<td data-toggle="tooltip" title="磁盘io带宽使用百分比">iobusy</td>
				<td data-toggle="tooltip" title="网络入流量 单位K/s">入网</td>
				<td data-toggle="tooltip" title="网络出流量 单位k/s">出网</td>
				<td data-toggle="tooltip" title="tcp estab连接数">连接</td>
				<td data-toggle="tooltip" title="tcp time wait连接数">等待</td>
				<td>机器类型</td>
				<td>收集时间</td>
				<td>操作</td>
			</tr>
		</thead>
		<tbody>
            <#if response.empty>
			     <tr>
                    <td colspan="17"class="text-center" >
                    	暂无数据
                    </td>
                <tr>
			<#else>
				<#list response.result as server>
					<tr>
						<td><input class="pointer" type="checkbox" name="monitor" value="${server.ip}" onclick="checkThis(this)" /></td>
						<td>${server_index+1}</td>
						<td><a href="#" onclick="setIp('${server.ip}')" data-target="#monitorModal" data-toggle="modal">${server.ip}</a></td>
						<td>${server.host!}</td>
						<td>${server.cpus!}</td>
						<td>
							<#if server.mtotal != 0>
								<div class="progress" style="margin-bottom:10px;">
		                         	<div class="progress-bar progress-bar-info" aria-valuenow="60"  aria-valuemax="100" aria-valuemin="0" style="width:${(server.mtotal-server.mfree)*100.0/server.mtotal}%;">
		        						<span>${((server.mtotal-server.mfree)/1024)?string("#.#")}g/${(server.mtotal/1024)?string("#.#")}g</span>
		        					</div>
		        				</div>
							</#if>
						</td>
						<td>${server.cload1!}</td>
						<td>${server.dread!}</td>
						<td>${server.dwrite!}</td>
						<td>${server.diops!}</td>
						<td>${server.dbusy!}%</td>
						<td>${server.nin!}</td>
						<td>${server.nout!}</td>
						<td>${server.tuse!}</td>
						<td>${server.twait!}</td>
						<td>
							<#if server.machineType??>
								${server.machineTypeName}
							<#else>
								<button type="button" data-toggle="tooltip" title="添加机器类型" onclick="updateServer('${server.ip}');" class="btn-xs btn-success"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button>
							</#if>
						</td>
						<td>
						<#if server.cdate??>
							${server.cdate!} ${server.ctime?substring(0,2)}:${server.ctime?substring(2)}
						</#if>
						</td>
						<td>
							<button type="button" onclick="deleteServer('${server.ip}');" class="btn-xs btn-warning"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button>
							<button type="button" data-toggle="tooltip" title="修改预警阈值" onclick="updateServerWarnConfig('${server.ip}');" class="btn-xs btn-info"><span class="glyphicon glyphicon-bell" aria-hidden="true"></span></button>
						</td>
					</tr>
				</#list>
			</#if>
		</tbody>
	</table>
</div>

<!-- 添加机器 -->
<div id="addServerModal" class="modal fade" tabindex="-1" data-width="400">
	<div class="modal-dialog" style="width:800px;">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title">添加机器</h4>
			</div>
			<form class="form-horizontal form-bordered form-row-stripped" id="addServerForm">
				<div class="modal-body">
					<div class="row">
						<div class="col-md-12">
							<div class="form-body">
								<div class="form-group">
									<label class="control-label col-md-2"> 初始化脚本: </label>
									<div class="col-md-9">
										<textarea type="text" rows="5" class="form-control" readonly>1. useradd ${username}
2. passwd ${username} （密码为：${password}）
3. echo "${username}     ALL=(ALL)       NOPASSWD: ALL" >> /etc/sudoers
4. sed -i "s/Defaults    requiretty/#Defaults    requiretty/g" /etc/sudoers</textarea>
									</div>
								</div>
								<div id="producerGroup" class="form-group">
									<label class="control-label col-md-2"> 机器IP: </label>
									<div class="col-md-5">
										<input type="text" id="ipInput" name="ip" value="" placeholder="IP" class="form-control" />
									</div>
								</div>
								<div id="machineTypeGroup" class="form-group">
									<label class="control-label col-md-2"> 机器类型: </label>
							        <div class="col-md-5">
			    						<select id="machineTypeSearchSelect" class="selectpicker" title="请选择"  name="machineType"></select>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" data-dismiss="modal" class="btn" >取消</button>
					<button type="button" class="btn btn-primary" id="addTopicBtn" onclick="addServer()">确定</button>
				</div>
			</form>
		</div>
	</div>
</div>
<!-- 修改机器报警配置 -->
<div id="addServerAlarmConfigModal" class="modal fade" tabindex="-1" data-width="400">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title">配置预警阈值</h4>
			</div>
			<form class="form-horizontal form-bordered form-row-stripped" id="addAlarmConfigForm">
				<div class="modal-body">
					<div class="row">
						<div class="col-md-12">
							<div class="form-body">
								<fieldset>
           							<legend>待配置IP</legend>
									<div class="form-group">
										<div class="col-md-10" style="padding-left:90px">
											<textarea id="toBeConfiguredIpList" type="text" name="ipList" rows="3" class="form-control" readonly></textarea>
										</div
									</div>
								</fieldset>
								<fieldset>
           							<legend>负载</legend>
									<div class="form-group">
										<label class="control-label col-md-4"> CPU使用率(User): </label>
										<div class="col-md-6">
											<div class="input-group">
												<input type="text" id="cpuUseRateInput" name="cpuUsageRate" value="" placeholder="建议70%" class="form-control" />
												<span class="input-group-addon">%</span>
		    								</div>
										</div>
									</div>
									<div class="form-group">
										<label class="control-label col-md-4"> 一分钟Load: </label>
										<div class="col-md-6">
											<input type="text" id="load1Input" name="load1" value="" placeholder="建议逻辑核数*80%" class="form-control" />
										</div>
									</div>
								</fieldset>
								<fieldset>
           							<legend>内存</legend>
									<div class="form-group">
										<label class="control-label col-md-4"> 内存使用率: </label>
										<div class="col-md-6">
											<div class="input-group">
												<input type="text" id="memoryUseRateInput" name="memoryUsageRate" value="" placeholder="建议为60%" class="form-control" />
												<span class="input-group-addon">%</span>
		    								</div>
										</div>
									</div>
								</fieldset>
								<fieldset>
           							<legend>网络</legend>
									<div class="form-group">
										<label class="control-label col-md-4"> 连接数: </label>
										<div class="col-md-6">
											<input type="text" id="connectInput" name="connect" value="" class="form-control" />
										</div>
									</div>
									<div class="form-group">
										<label class="control-label col-md-4" data-placement="right" data-toggle="modal" title="TIME_WAIT状态的连接数"> 等待关闭数: </label>
										<div class="col-md-6">
											<input type="text" id="waitInput" name="wait" value="" class="form-control" />
										</div>
									</div>
									<div class="form-group">
										<label class="control-label col-md-4"> 入流量: </label>
										<div class="col-md-6">
											<div class="input-group">
												<input type="text" id="netInInput" name="netIn" class="form-control" />
												<span class="input-group-addon">k/s</span>
		    								</div>
										</div>
									</div>
									<div class="form-group">
										<label class="control-label col-md-4"> 出流量: </label>
										<div class="col-md-6">
											<div class="input-group">
												<input type="text" id="netOutInput" name="netOut" class="form-control" />
												<span class="input-group-addon">k/s</span>
		    								</div>
										</div>
									</div>
								</fieldset>
								<fieldset>
           							<legend>磁盘</legend>
									<div class="form-group">
										<label class="control-label col-md-4" data-placement="right" data-toggle="modal" title="io繁忙程度，最大100%，同iostat %util字段"> iobusy: </label>
										<div class="col-md-6">
											<div class="input-group">
												<input type="text" id="ioBusyInput" name="iobusy" value="" placeholder="建议20%" class="form-control" />
												<span class="input-group-addon">%</span>
		    								</div>
										</div>
									</div>
									<div class="form-group">
										<label data-placement="right" data-toggle="modal" title="磁盘io速率：交互次数/s" class="control-label col-md-4"> iops: </label>
										<div class="col-md-6">
											<div class="input-group">
												<input type="text" id="iopsInput" name="iops" class="form-control" />
												<span class="input-group-addon">次/秒</span>
		    								</div>
										</div>
									</div>
									<div class="form-group">
										<label  class="control-label col-md-4"> 使用率: </label>
										<div class="col-md-6">
											<div class="input-group">
												<input type="text" id="ioUsageRateInput" name="ioUsageRate" placeholder="各分区使用率，建议90%" class="form-control" />
												<span class="input-group-addon">%</span>
		    								</div>
										</div>
									</div>
								</fieldset>
							</div>
						</div>
					</div>
				</div>
				<div class="modal-footer">
					<button type="button" data-dismiss="modal" class="btn" >取消</button>
					<button type="button" class="btn btn-primary" onclick="submitUpdateServerAlarmConfig()" id="addAlarmConfigBtn">确定</button>
				</div>
			</form>
		</div>
	</div>
</div>
<!-- 删除 -->
<div class="modal fade" id="deleteServerModal" aria-hidden="true">  
  <div class="modal-dialog">  
    <div class="modal-content message_align">  
      <div class="modal-header">  
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>  
        <h4 class="modal-title">确定要删除当前服务器吗？</h4>  
      </div>  
		<form class="form-horizontal form-bordered form-row-stripped">
			<div class="modal-body">
				<div class="row">
					<!-- 控件开始 -->
					<div class="col-md-12">
						<!-- form-body开始 -->
						<div class="form-body">
							<div class="form-group">
								<label class="control-label col-md-3"> IP: </label>
								<div class="col-md-5">
									<input type="text" id="deleteIpInput" class="form-control" readonly="readonly"/>
								</div>
							</div>
						</div>
						<!-- form-body 结束 -->
					</div>
					<div id="info"></div>
					<!-- 控件结束 -->
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" data-dismiss="modal" class="btn" >取消</button>
				<button type="button" id="deleteServerBtn" onclick="deleteServerConfirm()" class="btn btn-primary">确定</button>
			</div>
		</form>
    </div>
  </div>
</div>
<!-- 修改 -->
<div class="modal fade" id="updateServerModal" aria-hidden="true">  
  <div class="modal-dialog">  
    <div class="modal-content message_align">  
      <div class="modal-header">  
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>  
        <h4 class="modal-title"><b id="updateIpInput"></b> 服务器类型修改</h4>  
      </div>  
		<form class="form-horizontal form-bordered form-row-stripped">
			<div class="modal-body">
				<div class="row">
					<!-- 控件开始 -->
					<div class="col-md-12">
						<!-- form-body开始 -->
						<div class="form-body">
							<div class="form-group">
								<label class="control-label col-md-3"> 机器类型: </label>
								<div class="col-md-5">
									<select id="machineTypeSelect" class="selectpicker" title="请选择"  name="machineType"></select>
								</div>
							</div>
						</div>
						<!-- form-body 结束 -->
					</div>
					<!-- 控件结束 -->
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" data-dismiss="modal" class="btn" >取消</button>
				<button type="button" id="updateServerBtn" onclick="updateServerConfirm()" class="btn btn-primary">确定</button>
			</div>
		</form>
    </div>
  </div>
</div>
<!-- 监控 -->
<div id="monitorModal" class="modal fade" tabindex="-1">
	<div class="modal-dialog" style="width:90%;height:90%;">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<h4 class="modal-title"><b id="ipB"></b> 状况</h4>
			</div>
			<div class="container" style="padding:0px;margin:0px;">
			    <div class="tabbable-custom">
			        <ul class="nav nav-pills" id="server_app_tabs">
			            <li class="active"><a href="#overview" data-url="${request.contextPath}/admin/server/overview" data-toggle="tab">概览</a></li>
			            <li><a href="#cpu" data-url="${request.contextPath}/admin/server/cpu" data-toggle="tab">cpu</a></li>
			            <li><a href="#net" data-url="${request.contextPath}/admin/server/net" data-toggle="tab">net</a></li>
			        	<li><a href="#disk" data-url="${request.contextPath}/admin/server/disk" data-toggle="tab">disk</a></li>
			        </ul>
			        <div class="tab-content">
			            <div class="tab-pane active" id="overview">
			            </div>
			            <div class="tab-pane" id="cpu">
			            </div>
			            <div class="tab-pane" id="net">
			            </div>
			            <div class="tab-pane" id="disk">
			            </div>
			        </div>
			    </div>
			</div>
		</div>
	</div>
</div>

<input type="hidden" id="ipInput">

<script>
$(function(){
	// 适应小屏幕
	if(window.screen.width == 1366){
		$("#serverTable").addClass('tableUpdate');
	}
	//初始化
	initMachineTypeList();
});
//全选
function checkAll(t){
	if(t.checked){
		$("input[name='monitor']").each(function(){ //反选 
			       $(this).prop("checked",true);    
			    });
	}else{
		$("input[name='monitor']").each(function(){ //反选 
			       $(this).prop("checked",false); 
			    });  
	} 
}
//单选操作
function checkThis(t) {
	if(t.checked){
		$(this).prop("checked",false);	
	}else{
		$(this).prop("checked",true);
	}  
}
//批量修改预警配置
function batchUpdateServerAlarmConfig(){
	if(!$("input[name='monitor']:checked").val()){
		alert("请至少选择一个机器！");
		return;
	}	
	var str = "";
	$("input:checkbox[name='monitor']:checked").each(function(i) {
		var val = $(this).val();
		if($(this).val() != "on"){
			str = val+" , "+str;
		}
	});
	$("#addAlarmConfigForm")[0].reset();
	$("#toBeConfiguredIpList").val(str.substring(0,str.length-3));
	$("#addServerAlarmConfigModal").modal('show');
}
//发送更新请求
function submitUpdateServerAlarmConfig(){
	// 兼容用户不关心的预警项，故此处只是简单的数据校验
	if(!checkData()){
		return;
	};
	disable("addAlarmConfigBtn");
	$.post('${request.contextPath}/admin/server/alarm/config/update',
			$("#addAlarmConfigForm").serialize(),
	        function(data){
	            if(data.status == 200){
	            	toastr.success("修改成功，将自动刷新！");  
	            	reload(3000);
			    }else{
			    	toastr.error("修改失败！"+data.message);
			    	enable("addAlarmConfigBtn");
			    }
        }, 'json');
}

// 单个报警配置
function updateServerWarnConfig(ip){
	$.get('${request.contextPath}/admin/server/alarm/config/detail',
			{
				ip: ip
			},
	        function(data){
	            if(data.status == 200){
	            	var config = data.result;
	            	$("#toBeConfiguredIpList").val(ip);
	            	$("#cpuUseRateInput").val(config.cpuUsageRate > 0 ? config.cpuUsageRate : '');
	            	$("#load1Input").val(config.load1 > 0 ? config.load1 : '');
	            	$("#memoryUseRateInput").val(config.memoryUsageRate > 0 ? config.memoryUsageRate : '');
	            	$("#connectInput").val(config.connect > 0 ? config.connect : '');
	            	$("#waitInput").val(config.wait > 0 ? config.wait : '');
	            	$("#netInInput").val(config.netIn > 0 ? config.netIn : '');
	            	$("#netOutInput").val(config.netOut > 0 ? config.netOut : '');
	            	$("#ioBusyInput").val(config.iobusy > 0 ? config.iobusy : '');
	            	$("#iopsInput").val(config.iops > 0 ? config.iops : '');
	            	$("#ioUsageRateInput").val(config.ioUsageRate > 0 ? config.ioUsageRate : '');
			    }else{
			    	$("#addAlarmConfigForm")[0].reset();
			    	$("#toBeConfiguredIpList").val(ip);
			    }
        }, 'json');
	$("#addServerAlarmConfigModal").modal('show');
}
/**
 * 添加机器
 */
function addServer(){
	if(!$("#ipInput").val()){
		alert("请输入ip");
		return;
	}
	if(!$("#machineTypeSearchSelect").val()){
		alert("请选择机器类型");
		return;
	}
	disable("addTopicBtn");
	$.post('${request.contextPath}/admin/server/add',
			{
				ip: $("#ipInput").val(),
				type : $("#machineTypeSearchSelect").val()
			},
	        function(data){
	            if(data.status == 200){
	            	toastr.success("添加成功，将自动刷新！");  
	            	reload(3000);
			    }else{
			    	toastr.error("添加失败！"+data.message);  
			    	enable("addTopicBtn");
			    }
        }, 'json');
}

$('#server_app_tabs a').click(function (e) {
    e.preventDefault();
    var href = this.hash;
    var url = $(this).attr("data-url");
    var ip = $("#ipInput").val();
    var date = $("#dateInput").val();
    if(ip){
        if(url.indexOf("?") == -1){
        	url += "?";
        }
    	url += "&ip="+ip;
    }
    if(date){
        if(url.indexOf("?") == -1){
        	url += "?";
        }
    	url += "&date="+date;
    }
    $.get(url, function (result) {
    	$(href).html(result);
    });
});
function setIp(ip){
	$("#ipInput").val(ip);
	$("#ipB").html(ip);
}
$('#monitorModal').on('shown.bs.modal', function (e) {
	$("#server_app_tabs li.active a").click();
})
//删除机器
function deleteServer(ip){
	$("#deleteIpInput").val(ip);
	$("#deleteServerModal").modal('show');
}
//发送删除请求
function deleteServerConfirm(){
	disable("deleteServerBtn");
	$.get('${request.contextPath}/admin/server/delete',
		{
			ip: $("#deleteIpInput").val()
		},
        function(data){
            if(data.status == 200){
            	toastr.success("删除成功！即将刷新页面！");
            	reload(3000);            	
		    }else{
		    	toastr.error("删除失败！"+data.message);  
		    	enable("deleteServerBtn");
		    }
    }, 'json');
}
//修改机器
function updateServer(ip){
	$("#updateIpInput").text(ip);
	$("#updateServerModal").modal('show');
}
//发送修改请求
function updateServerConfirm(){
	disable("updateServerBtn");
	$.post('${request.contextPath}/admin/server/update',
		{
			ip: $("#updateIpInput").text(),
			type: $("#machineTypeSelect").val()
		},
        function(data){
            if(data.status == 200){
            	toastr.success("修改成功！即将刷新页面！");
            	reload(3000);            	
		    }else{
		    	toastr.error("修改失败！"+data.message);  
		    	enable("updateServerBtn");
		    }
    }, 'json');
}
// 初始化机器类型列表
function initMachineTypeList(){
	$.get('${request.contextPath}/admin/server/type',
	        function(data){
	            if(data.status == 200){
	            	var content = "";
	            	for(var i in data.result){
	            		var type = data.result[i];
	            		content += "<option value='"+type.key+"'>"+type.value+"</option>";	
	            	}
	        		$("#machineTypeSelect").html(content);
	        		$("#machineTypeSearchSelect").html(content);
	        		$("#machineTypeSelect").selectpicker('refresh');
	        		$("#machineTypeSearchSelect").selectpicker('refresh');
			    }else{
			    	toastr.error("数据获取失败！"+data.message);  
			    }
        }, 'json');
}
// 校验服务器监控指标的配置
function checkData(){
	var arr = ["cpuUseRateInput", "load1Input", "memoryUseRateInput", "connectInput", 
		"waitInput", "netInInput", "netOutInput", "ioBusyInput", "iopsInput", "ioUsageRateInput"];
	 for(var i=0;i<arr.length;i++){
		if($("#"+arr[i]).val() && $("#"+arr[i]).val() <= 0){
			alert("配置项允许为空但所填项均要大于0");
			return false;
		}
	}
	 return true;
}

</script>